package org.apache.cordova.common;

import com.example.questionnaire.MyApplication;
import com.example.questionnaire.api.TestPapersApi;
import com.example.questionnaire.bean.TestPagerBean;
import com.example.questionnaire.event.GotoScreensaverEvent;
import com.example.questionnaire.event.StopScreensaverEvent;
import com.example.questionnaire.utils.PrefUtils;
import com.example.questionnaire.utils.StringUtils;
import com.example.questionnaire.utils.SystemUtil;
import com.example.questionnaire.utils.UDPUtils;
import com.google.gson.Gson;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * author: liweixing
 * date: 2018/1/14
 */

public class CommonPlugin extends CordovaPlugin {

    public static final String BIG_SCREEN_IP = "big_screen_ip";//大屏ip
    public static final String BIG_SCREEN_PORT = "big_screen_port";//大屏端口
    public static final String BARRAGE_IP = "barrage_ip";//弹幕ip
    public static final String BARRAGE_PORT = "barrage_port";//弹幕端口
    public static final String FLOOR = "floor";// String类型
    public static final String SCREENSAVER = "screensaver";//屏保
    public static final String PLACE = "place";//地点
    public static final String REQUESTADDRESS = "requestAddress";//网络请求地址
    public static final String PARAMS = "params";//参数
    public static final String ID = "id";//
    public static final String FACTORYID = "factoryId";//
    public static final String FORFLOOR = "forfloor";//
    private boolean isRequestSuccess;


    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {

        if ("getInformation".equals(action)) {
            JSONObject json = new JSONObject();
            String id = PrefUtils.getString(ID, "");
            String factoryId = PrefUtils.getString(FACTORYID, "");
            String forfloor = PrefUtils.getString(FORFLOOR, "");

            String big_screen_ip = PrefUtils.getString(BIG_SCREEN_IP, "");
            String big_screen_port = PrefUtils.getString(BIG_SCREEN_PORT, "");
            String barrage_ip = PrefUtils.getString(BARRAGE_IP, "");
            String barrage_port = PrefUtils.getString(BARRAGE_PORT, "");
            String floor = PrefUtils.getString(FLOOR, "");
            String screensaver = PrefUtils.getString(SCREENSAVER, "");
            String place = PrefUtils.getString(PLACE, "");

            json.put(ID, id);
            json.put(FACTORYID, factoryId);
            json.put(FORFLOOR, forfloor);

            json.put(BIG_SCREEN_IP, big_screen_ip);
            json.put(BIG_SCREEN_PORT, big_screen_port);
            json.put(BARRAGE_IP, barrage_ip);
            json.put(BARRAGE_PORT, barrage_port);
            json.put(FLOOR, floor);
            json.put(SCREENSAVER, screensaver);
            json.put(PLACE, place);

            callbackContext.success(json.toString());
            return true;
        } else if ("sendUDPMessage".equals(action)) {
            try {
                JSONObject json = args.getJSONObject(0);
                String blessings = json.getString("blessings");
                String instructions = json.getString("instructions");
                if (!StringUtils.isEmpty(blessings)) {
                    UDPUtils.sendMessage(blessings, 2);
                }
                UDPUtils.sendMessage(instructions, 1);
//            UDPUtils.sendMessage(instructions, 1);
            } catch (Exception e) {
                e.printStackTrace();
                callbackContext.error(0);
                return true;
            }
            callbackContext.success(1);
            return true;
        } else if ("saveSetupInformation".equals(action)) {
            /*
             information:  Json类型 {
             "big_screen_ip": 大屏ip String类型
             "big_screen_port": 大屏端口 String类型
             "barrage_ip": 弹幕ip String类型
             "barrage_port": 弹幕端口 String类型
             "floor":  楼层 String类型
             "screensaver": 屏保 String类型
             "place": 地点 String类型
             "requestAddress": 网络请求地址 String类型 }
             */
            String big_screen_ip = "";
            String big_screen_port = "";
            String barrage_ip = "";
            String barrage_port = "";
            String floor = "";
            String screensaver = "";
            String place = "";
            String requestAddress = "";
            try {
                JSONObject json = args.getJSONObject(0);
                big_screen_ip = json.getString(BIG_SCREEN_IP);
                big_screen_port = json.getString(BIG_SCREEN_PORT);
                barrage_ip = json.getString(BARRAGE_IP);
                barrage_port = json.getString(BARRAGE_PORT);
                floor = json.getString(FLOOR);
                screensaver = json.getString(SCREENSAVER);
                try {
                    place = json.getString(PLACE);
                } catch (JSONException e) {
                    e.printStackTrace();
                    callbackContext.error("请选择地址！");
                    return true;
                }
                requestAddress = json.getString(REQUESTADDRESS);

                String result = "";
                if (StringUtils.isEmpty(big_screen_ip)) {
                    result = "大屏IP地址";
                } else if (StringUtils.isEmpty(big_screen_port)) {
                    result = "大屏端口";
                } else if (StringUtils.isEmpty(barrage_ip)) {
                    result = "弹幕IP地址";
                } else if (StringUtils.isEmpty(barrage_port)) {
                    result = "弹幕端口";
                } else if (StringUtils.isEmpty(floor)) {
                    result = "楼层";
                } else if (StringUtils.isEmpty(screensaver)) {
                    result = "屏保时间";
                } else if (StringUtils.isEmpty(place)) {
                    result = "地址";
                }

                if (!StringUtils.isEmpty(result)) {
                    callbackContext.error(result + "不能为空！");
                    return true;
                }

                String ipRegex = "^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$";
                if (!big_screen_ip.matches(ipRegex)) {
                    callbackContext.error("大屏IP地址输入有误！");
                    return true;
                }
                if (!barrage_ip.matches(ipRegex)) {
                    callbackContext.error("弹幕IP地址输入有误！");
                    return true;
                }

                String portRegex = "([0-9]|[1-9]\\d|[1-9]\\d{2}|[1-9]\\d{3}|[1-5]\\d{4}|6[0-4]\\d{3}|65[0-4]\\d{2}|655[0-2]\\d|6553[0-5])";
                if (!big_screen_port.matches(portRegex)) {
                    callbackContext.error("大屏端口请输入0到65535的整数！");
                    return true;
                }
                if (!barrage_port.matches(portRegex)) {
                    callbackContext.error("弹幕端口请输入0到65535的整数！");
                    return true;
                }

                String floorRegex = "[-]?[1-9]*[fF]";
                if (!floor.matches(floorRegex)) {
                    callbackContext.error("请输入正确的楼层！");
                    return true;
                }

                String screensaverRegex = "[1-9][0-9]*[sS]";
                if (!screensaver.matches(screensaverRegex)) {
                    callbackContext.error("请输入正确的屏保时间！");
                    return true;
                }

                PrefUtils.setString(BIG_SCREEN_IP, big_screen_ip);
                PrefUtils.setString(BIG_SCREEN_PORT, big_screen_port);
                PrefUtils.setString(BARRAGE_IP, barrage_ip);
                PrefUtils.setString(BARRAGE_PORT, barrage_port);
                PrefUtils.setString(FLOOR, floor);
                PrefUtils.setString(SCREENSAVER, screensaver);
                PrefUtils.setString(PLACE, place);
                PrefUtils.setString(REQUESTADDRESS, requestAddress);
            } catch (Exception e) {
                e.printStackTrace();
                callbackContext.error(e.toString());
                return true;
            }
            requestTestPapers(callbackContext, place, floor, requestAddress);
            return true;
        } else if ("gotoScreensaver".equals(action)) {
            EventBus.getDefault().post(new GotoScreensaverEvent(true));
            return true;
        } else if ("getIPandMAC".equals(action)) {
            JSONObject jsonObject = new JSONObject();
            try {
                String ipAddress = SystemUtil.getIPAddress(MyApplication.application);
                String macAddress = SystemUtil.getMacAddress();
                jsonObject.put("ip", ipAddress);
                jsonObject.put("mac", macAddress);
            } catch (Exception e) {
                e.printStackTrace();
                callbackContext.error(e.toString());
                return true;
            }
            callbackContext.success(jsonObject.toString());
            return true;
        } else if ("stopScreensaver".equals(action)) {
            EventBus.getDefault().post(new StopScreensaverEvent());
            return true;
        }
        return true;
    }

    private String getRequestAddress(String address) {
        if (StringUtils.isEmpty(address)) {
            return "";
        }
        if (address.contains(":")) {
            int index01 = address.indexOf(":");
            int index02 = address.lastIndexOf(":");
            if (index02 > index01) {
                String substring = address.substring(0, index02);
                return substring;
            }
        }
        return "";
    }

    /**
     * 获取试卷资料
     *
     * @param callbackContext
     * @param place
     * @param floor
     */
    private void requestTestPapers(CallbackContext callbackContext, String place, String floor, String baseUrl) {
        //http://172.20.71.147/vsd/queslistRlQuestion/1/1
        if (!StringUtils.isEmpty(baseUrl)) {
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(7, TimeUnit.SECONDS)
                    .writeTimeout(7, TimeUnit.SECONDS)
                    .readTimeout(7, TimeUnit.SECONDS)
                    .build();

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .client(okHttpClient)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();

            TestPapersApi api = retrofit.create(TestPapersApi.class);

            int placeNum = 0;
            if ("营口".equals(place)) {
                placeNum = 2;
            } else if ("新会".equals(place)) {
                placeNum = 1;
            }
            String replaceFloor;
            if (floor.contains("F")) {
                replaceFloor = floor.replace("F", "");
            } else {
                replaceFloor = floor.replace("f", "");
            }
            String params = "factoryId=" + placeNum + "&forfloor=" + replaceFloor;
            int finalPlaceNum = placeNum;

            isRequestSuccess = false;
            api.get("/vsd/queslistRlQuestion/" + placeNum + "/" + replaceFloor)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<ResponseBody>() {
                        @Override
                        public void accept(ResponseBody responseBody) throws Exception {
                            isRequestSuccess = true;
                            // 这里保存字段
                            String result = responseBody.string();
                            JSONObject jsonObject = new JSONObject(result);
                            JSONObject data = jsonObject.getJSONObject("data");
                            int id = data.getInt("id");

                            PrefUtils.setString(ID, "" + id);
                            PrefUtils.setString(FACTORYID, "" + finalPlaceNum);
                            PrefUtils.setString(FORFLOOR, replaceFloor);

                            String params01 = params + "&id=" + id;
                            PrefUtils.setString(PARAMS, params01);
                            callbackContext.success(params01);
                            EventBus.getDefault().post(new GotoScreensaverEvent(false));
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
//                            PrefUtils.setString(PARAMS, params);
                            if (isRequestSuccess) {
                                callbackContext.error("未配置试题！");
                            } else {
                                callbackContext.error("网络请求失败！");
                            }
//                            EventBus.getDefault().post(new GotoScreensaverEvent(false));
                        }
                    });
        }
    }
}
